﻿#include <iostream>
#include "component.h"
#include <vector>
#include <algorithm>

// 用于测试的组件结构体
struct Position {
    float x, y;
};

struct Velocity {
    float vx, vy;
};

// 用于高级测试的附加组件
struct Health {
    int current;
    int max;
};


// 测试函数
void testComponentManager() {
    std::cout << "--- Running componentManager Tests ---" << std::endl;

    componentsManager manager;

    // 1. 添加组件
    std::cout << "\n1. Testing addComponent..." << std::endl;
    uint64_t posId = manager.addComponent<1>(Position{ 10.0f, 20.0f });
    manager.addComponent<1>(Velocity{ 1.0f, 1.5f });
    manager.addComponent<2>(Position{ 30.0f, 40.0f });

    std::cout << "Added Position to entity 1 with ID: " << posId << std::endl;
    std::cout << "Added Velocity to entity 1" << std::endl;
    std::cout << "Added Position to entity 2" << std::endl;

    // 2. 获取组件
    std::cout << "\n2. Testing getComponents..." << std::endl;
    auto entity1Positions = manager.getComponents<1, Position>();
    if (!entity1Positions.empty()) {
        std::cout << "Entity 1 Position: x=" << entity1Positions[0]->x << ", y=" << entity1Positions[0]->y << std::endl;
    }

    auto entity2Positions = manager.getComponents<2, Position>();
    if (!entity2Positions.empty()) {
        std::cout << "Entity 2 Position: x=" << entity2Positions[0]->x << ", y=" << entity2Positions[0]->y << std::endl;
    }

    auto entity1Velocities = manager.getComponents<1, Velocity>();
    if (!entity1Velocities.empty()) {
        std::cout << "Entity 1 Velocity: vx=" << entity1Velocities[0]->vx << ", vy=" << entity1Velocities[0]->vy << std::endl;
    }

    // 3. 使用 forEach 遍历并修改组件
    std::cout << "\n3. Testing forEach..." << std::endl;
    std::cout << "Multiplying all Position.x by 2..." << std::endl;
    manager.forEach<Position>([](Position& pos) {
        pos.x *= 2;
        });

    // 验证修改
    auto updatedEntity1Pos = manager.getComponents<1, Position>();
    if (!updatedEntity1Pos.empty()) {
        std::cout << "Updated Entity 1 Position: x=" << updatedEntity1Pos[0]->x << std::endl;
    }
    auto updatedEntity2Pos = manager.getComponents<2, Position>();
    if (!updatedEntity2Pos.empty()) {
        std::cout << "Updated Entity 2 Position: x=" << updatedEntity2Pos[0]->x << std::endl;
    }


    // 4. 移除组件
    std::cout << "\n4. Testing eraseComponent..." << std::endl;
    try {
        manager.eraseComponent<Position>(posId);
        std::cout << "Successfully erased Position from entity 1." << std::endl;
    }
    catch (const std::runtime_error& e) {
        std::cout << "Error erasing component: " << e.what() << std::endl;
    }

    // 验证移除
    auto finalEntity1Positions = manager.getComponents<1, Position>();
    if (finalEntity1Positions.empty()) {
        std::cout << "Entity 1 has no Position component, as expected." << std::endl;
    }

    // 5. 测试移除不存在的组件
    std::cout << "\n5. Testing exception on erasing a removed component..." << std::endl;
    try {
        manager.eraseComponent<Position>(posId);
    }
    catch (const std::runtime_error& e) {
        std::cout << "Caught expected exception: " << e.what() << std::endl;
    }


    std::cout << "\n--- componentManager Tests Finished ---" << std::endl;
}

// 更复杂的测试函数
void testComponentManagerAdvanced() {
    std::cout << "\n--- Running componentManager Advanced Tests ---" << std::endl;
    componentsManager manager;

    // 1. 测试大量组件的添加和删除，以触发内存整理
    std::cout << "\n1. Testing memory recycling and arrangement..." << std::endl;
    const int healthComponentCount = 1000;
    std::vector<uint64_t> healthComponentIds;
    std::cout << "Adding " << healthComponentCount << " Health components to entity 10..." << std::endl;
    for (int i = 0; i < healthComponentCount; ++i) {
        healthComponentIds.push_back(manager.addComponent<10>(Health{ i, i }));
    }

    // 删除大约80%的组件，这应该会触发arragneFreeMemory
    int removalCount = static_cast<int>(healthComponentCount * 0.8);
    std::cout << "Erasing " << removalCount << " Health components to trigger memory arrangement..." << std::endl;
    for (int i = 0; i < removalCount; ++i) {
        manager.eraseComponent<Health>(healthComponentIds[i]);
    }

    std::cout << "Adding more components to test recycled memory slots..." << std::endl;
    // 再次添加一些组件，检查是否能复用已释放的内存
    uint64_t newHealthId = manager.addComponent<10>(Health{ 999, 999 });
    std::cout << "Added a new Health component with ID: " << newHealthId << std::endl;

    // 验证剩余组件和新组件的数据完整性
    int remainingCount = 0;
    manager.forEach<Health>([&remainingCount, &removalCount](Health& health) {
        if (health.current >= removalCount) { // 检查未被删除的组件
            remainingCount++;
        }
        else if (health.current == 999) { // 检查新添加的组件
            remainingCount++;
        }
    });
    std::cout << "Verified " << remainingCount << " components after removal and re-addition." << std::endl;
    if (remainingCount != (healthComponentCount - removalCount + 1)) {
        std::cout << "ERROR: Data integrity check failed!" << std::endl;
    }
    else {
        std::cout << "Data integrity check passed." << std::endl;
    }

    // 2. 测试实体容量扩展
    std::cout << "\n2. Testing entity capacity expansion..." << std::endl;
    // MAX_ENTITIES_DEFAULT 默认为 1024。添加组件到 entity 1025 会触发扩展。
    try {
        manager.addComponent<1025>(Position{ 1.0f, 1.0f });
        std::cout << "Successfully added component to entity 1025, triggering capacity expansion." << std::endl;
        auto positions = manager.getComponents<1025, Position>();
        if (!positions.empty() && positions[0]->x == 1.0f) {
            std::cout << "Verified component on new entity." << std::endl;
        }
    }
    catch (const std::exception& e) {
        std::cout << "ERROR: Exception during entity capacity expansion test: " << e.what() << std::endl;
    }

    // 3. 测试同一实体上的多个同类型组件
    std::cout << "\n3. Testing multiple components of the same type on one entity..." << std::endl;
    manager.addComponent<20>(Position{100.f, 100.f});
    manager.addComponent<20>(Position{200.f, 200.f});
    
    auto allPositions = manager.getComponents<20, Position>();
    std::cout << "Entity 20 has " << allPositions.size() << " Position components." << std::endl;
    if (allPositions.size() == 2) {
        std::cout << "Verified: Correct number of components found." << std::endl;
        // 检查值是否正确 (顺序不保证)
        bool found100 = false;
        bool found200 = false;
        for (const auto* pos : allPositions) {
            if (pos->x == 100.f) found100 = true;
            if (pos->x == 200.f) found200 = true;
        }
        if (found100 && found200) {
            std::cout << "Verified: All component instances have correct data." << std::endl;
        } else {
            std::cout << "ERROR: Data mismatch in multiple components." << std::endl;
        }
    } else {
        std::cout << "ERROR: Incorrect number of components found." << std::endl;
    }

    std::cout << "\n--- componentManager Advanced Tests Finished ---" << std::endl;
}

// 新增：边界与健壮性测试
void testComponentManagerEdgeCases() {
    std::cout << "\n--- Running componentManager Edge-Case Tests ---" << std::endl;
    componentsManager manager;

    // 1) 单实体组件列表扩容（>63）
    std::cout << "\n1) Entity component-list growth..." << std::endl;
    for (int i = 0; i < 70; ++i) {
        manager.addComponent<30>(Position{ static_cast<float>(i), static_cast<float>(i) });
    }
    auto e30Pos = manager.getComponents<30, Position>();
    std::cout << "Entity 30 Position count: " << e30Pos.size() << std::endl;
    if (e30Pos.size() != 70) {
        std::cout << "ERROR: Entity component-list growth failed." << std::endl;
    }

    // 2) forEach 跳过已移除 + 空间复用与稳定ID递增
    std::cout << "\n2) forEach skips removed + reuse locations with monotonic IDs..." << std::endl;
    std::vector<uint64_t> hIds;
    for (int i = 0; i < 5; ++i) {
        hIds.push_back(manager.addComponent<60>(Health{ i, i }));
    }
    manager.eraseComponent<Health>(hIds[1]);
    manager.eraseComponent<Health>(hIds[3]);
    int aliveHealth = 0;
    manager.forEach<Health>([&](Health&) { aliveHealth++; });
    std::cout << "Alive Health count after removals: " << aliveHealth << std::endl;
    if (aliveHealth != 3) {
        std::cout << "ERROR: forEach should skip removed instances." << std::endl;
    }
    uint64_t hNew = manager.addComponent<60>(Health{ 999, 999 });
    uint32_t oldMaxStable = 0;
    for (auto id : hIds) oldMaxStable = std::max<uint32_t>(oldMaxStable, static_cast<uint32_t>(id & 0xFFFFFFFF));
    if (static_cast<uint32_t>(hNew & 0xFFFFFFFF) <= oldMaxStable) {
        std::cout << "ERROR: New Health instance ID should be monotonically increasing." << std::endl;
    } else {
        std::cout << "OK: New Health instance got a higher stable ID and reused freed slot." << std::endl;
    }

    // 3) 跨内存块与 ID->地址映射表扩容（>1023）
    std::cout << "\n3) Cross-block allocation and instanceIdToAddress growth..." << std::endl;
    std::vector<uint64_t> bigHealthIds;
    bigHealthIds.reserve(1100);
    for (int i = 0; i < 1100; ++i) {
        try {
            bigHealthIds.push_back(manager.addComponent<61>(Health{ i, i }));
        }
        catch(std::runtime_error& e) {
            std::cout << "exception during large Health component addition: " << e.what() << std::endl;
            break;
		}
    }
    std::cout << "Added " << bigHealthIds.size() << " Health instances to entity 61." << std::endl;
    // 删除一个高位实例确保映射可用
    try {
        manager.eraseComponent<Health>(bigHealthIds.back());
        std::cout << "Erase on high-index Health succeeded (mapping OK)." << std::endl;
    } catch (const std::exception& e) {
        std::cout << "ERROR: Erasing high-index Health failed: " << e.what() << std::endl;
    }

    // 4) 中间删除与搬移后的正确性（同一实体多类型混合）
    std::cout << "\n4) Middle erase updates moved item index correctly..." << std::endl;
    uint64_t a = manager.addComponent<55>(Position{1.f, 1.f});
    uint64_t b = manager.addComponent<55>(Position{2.f, 2.f});
    uint64_t v = manager.addComponent<55>(Velocity{7.f, 8.f});
    uint64_t c = manager.addComponent<55>(Position{3.f, 3.f});
    // 删除中间的 b，会把最后的 c 搬到 b 的位置，并更新其索引标记
    manager.eraseComponent<Position>(b);
    auto e55Pos = manager.getComponents<55, Position>();
    bool has1 = false, has3 = false;
    for (auto* p : e55Pos) {
        if (p->x == 1.f) has1 = true;
        if (p->x == 3.f) has3 = true;
    }
    if (!(e55Pos.size() == 2 && has1 && has3)) {
        std::cout << "ERROR: Middle erase didn't leave expected Position set." << std::endl;
    }
    // 再删除被搬移的 c，若索引更新正确，应能删除成功
    try {
        manager.eraseComponent<Position>(c);
        std::cout << "OK: Erased moved Position (index updated correctly)." << std::endl;
    } catch (const std::exception& e) {
        std::cout << "ERROR: Failed to erase moved Position: " << e.what() << std::endl;
    }
    auto e55Pos2 = manager.getComponents<55, Position>();
    auto e55Vel = manager.getComponents<55, Velocity>();
    if (!(e55Pos2.size() == 1 && e55Vel.size() == 1)) {
        std::cout << "ERROR: Entity 55 expected 1 Position and 1 Velocity after deletions." << std::endl;
    }

    // 5) Mod 128 索引扫描：≥128 个组件
    std::cout << "\n5) Mod-128 index scanning with large component list..." << std::endl;
    std::vector<uint64_t> manyPosIds;
    manyPosIds.reserve(130);
    for (int i = 0; i < 130; ++i) {
        manyPosIds.push_back(manager.addComponent<70>(Position{ static_cast<float>(i), 0.f }));
    }
    // 删第一个，会把最后一个搬移到索引0，随后删除原最后一个的ID应成功（依赖步长128扫描）
    try {
        manager.eraseComponent<Position>(manyPosIds.front());
        manager.eraseComponent<Position>(manyPosIds.back());
        std::cout << "OK: Mod-128 scanning path works with moved last element." << std::endl;
    } catch (const std::exception& e) {
        std::cout << "ERROR: Mod-128 scanning path failed: " << e.what() << std::endl;
    }

    // 6) 类型不匹配删除
    std::cout << "\n6) Type mismatch on erase..." << std::endl;
    uint64_t hid = manager.addComponent<1>(Health{ 10, 10 });
    try {
        manager.eraseComponent<Position>(hid);
        std::cout << "ERROR: Expected type mismatch exception not thrown." << std::endl;
    } catch (const std::runtime_error& e) {
        std::cout << "Caught expected exception: " << e.what() << std::endl;
    }

    // 7) 伪造越界实例ID删除
    std::cout << "\n7) Out-of-range instance ID on erase..." << std::endl;
    uint16_t posTypeId = component::component<Position>::getId();
    uint64_t fakeOutOfRange = (static_cast<uint64_t>(1) << 48) |
                              (static_cast<uint64_t>(posTypeId) << 32) |
                              0xFFFFFFFEull;
    try {
        manager.eraseComponent<Position>(fakeOutOfRange);
        std::cout << "ERROR: Expected out-of-range exception not thrown." << std::endl;
    } catch (const std::runtime_error& e) {
        std::cout << "Caught expected exception: " << e.what() << std::endl;
    }

    // 8) 实体ID越界
    std::cout << "\n8) EntityId out of range..." << std::endl;
    try {
        manager.addComponent<65535>(Position{0.f, 0.f});
        std::cout << "ERROR: Expected EntityId out-of-range exception not thrown." << std::endl;
    } catch (const std::runtime_error& e) {
        std::cout << "Caught expected exception: " << e.what() << std::endl;
    }

    std::cout << "\n--- componentManager Edge-Case Tests Finished ---" << std::endl;
}

int main()
{
    // 运行基础测试
    testComponentManager();

    // 运行高级测试
    testComponentManagerAdvanced();

    // 运行边界与健壮性测试
    testComponentManagerEdgeCases();

    return 0;
}